const path = require("path");
const sassResourcesLoader = require("craco-sass-resources-loader");
const TerserPlugin = require("terser-webpack-plugin");
const CompressionWebpackPlugin = require("compression-webpack-plugin");
const ProgressBarPlugin = require("progress-bar-webpack-plugin"); // Added
const resolve = (dir) => path.resolve(__dirname, dir);

module.exports = {
  babel: {
    plugins: [
      ["import", { libraryName: "antd", style: true }],
      ...(process.env.NODE_ENV === "production"
        ? [["transform-remove-console", { exclude: ["error", "warn"] }]]
        : []),
    ],
  },
  devServer: {
    proxy: {
      "/api": "http://192.168.88.211:19312",
    },
  },
  webpack: {
    alias: {
      "@": resolve("src"),
      components: resolve("src/components"),
    },
    configure: (webpackConfig, { env }) => {
      // 生产环境配置
      if (env === "production") {
        // 混淆代码
        webpackConfig.optimization.minimize = true;
        webpackConfig.optimization.minimizer.push(
          new TerserPlugin({
            terserOptions: {
              compress: {
                drop_console: true,
              },
            },
          })
        );
        //启用Gzip
        webpackConfig.plugins.push(
          new CompressionWebpackPlugin({
            filename: "[path][base].gz",
            algorithm: "gzip",
            test: /\.(js|css|html|svg)$/,
            threshold: 10240,
            minRatio: 0.8,
          })
        );
        //将大文件抽离成chunk分离
        webpackConfig.optimization.splitChunks = {
          cacheGroups: {
            antd: {
              test: /[\\/]node_modules[\\/]antd[\\/]/,
              name: "chunk-antd",
              chunks: "all",
              enforce: true,
            },
          },
        };
        // 添加 exclude 选项以排除 serve 文件夹
        webpackConfig.module.rules.forEach((rule) => {
          if (rule.oneOf) {
            rule.oneOf.forEach((oneOfRule) => {
              if (
                oneOfRule.loader &&
                oneOfRule.loader.includes("babel-loader")
              ) {
                oneOfRule.exclude = /serve/;
              }
            });
          }
        });
        //加载进度
        webpackConfig.plugins.push(new ProgressBarPlugin());
      }
      //开发环境配置
      if (env === "development") {
  
      }
            //启用sourceMap
            webpackConfig.devtool = "source-map";

      return webpackConfig;
    },
  },
  plugins: [
    {
      plugin: sassResourcesLoader,
      options: {
        resources: "./src/style/variable.scss",
      },
    },
  ],
};
